package com.polaris.live.viewmodel.party

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.common.network.request
import com.polaris.live.common.network.state.ResultState
import com.polaris.live.constant.LiveConst
import com.polaris.live.im.sfs.COMMAND_LIVE_JOIN
import com.polaris.live.im.sfs.COMMAND_LIVE_QUIT
import com.polaris.live.im.sfs.bean.live.LiveJoinMessage
import com.polaris.live.im.sfs.bean.live.LiveQuitMessage
import com.polaris.live.im.sfs.core.SmartFoxQueueManager
import com.polaris.live.net.homeService
import com.polaris.live.resp.back_resp.DisplayUserBean
import com.polaris.live.resp.bean.ExitLiveBean
import com.polaris.live.ui.live.bean.LiveInitInfo
import com.polaris.live.utils.StartLiveProxy
import com.polaris.live.utils.parseLiveInfo
import com.polaris.live.viewmodel.party.base.BasePartyActivityModel
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull

/**
 * PartySpectatorModel  观众Model
 *
 * @author Created by 天晴 on 2024/2/24 11:15
 * @since 1.0.0
 **/
class PartySpectatorModel : BasePartyActivityModel() {

    //直播间滑动更多逻辑
    val liveLoadMoreLiveData = MutableLiveData<ResultState<DisplayUserBean>>()
    fun getLoadMore(@LiveConst.RequestType mRequestType: Int, anchorId: Long, delay: Long? = null) {
        viewModelScope.launch {
            if (delay != null) {
                delay(delay)
            }
            request({
                when (mRequestType) {
                    LiveConst.RequestLiveType.PARTY -> homeService.getLiveParty(anchorId)
                    LiveConst.RequestLiveType.GAME -> homeService.getLiveGame(anchorId)
                    else -> throw Exception("No mLiveType")
                }
            }, liveLoadMoreLiveData)
        }
    }

    //用户加入直播间
    val joinLiveLiveData = MutableLiveData<ResultState<LiveInitInfo>>()
    fun joinLive(anchorId: Long, password: String? = null, liveInitInfo: LiveInitInfo? = null, roomId: String? = null) {
        if (liveInitInfo != null) {
            joinLiveLiveData.value = ResultState.onAppSuccess(liveInitInfo)
            return
        }
        viewModelScope.launch {
            joinLiveLiveData.value = StartLiveProxy.launchLiveMessageState(anchorId, {
                SmartFoxQueueManager.sendLiveMessage(
                    COMMAND_LIVE_JOIN,
                    LiveJoinMessage(anchorId = anchorId, password = password, roomId = roomId)
                )
            }, {
                val room = getRoom()
                room?.parseLiveInfo()?.let { variable ->
                    LiveInitInfo(variable, room.userCount)
                }
            })
        }
    }

    //用户恢复加入直播间
    val recoverJoinLiveData = MutableLiveData<ResultState<LiveInitInfo>>()
    fun recoverJoinLive(anchorId: Long, password: String? = null, delay: Long? = null, roomId: String? = null) {
        viewModelScope.launch {
            if (delay != null && delay > 0) {
                delay(delay)
            }
            joinLiveLiveData.value = StartLiveProxy.launchLiveMessageState(anchorId, {
                SmartFoxQueueManager.sendLiveMessage(
                    COMMAND_LIVE_JOIN,
                    LiveJoinMessage(anchorId = anchorId, password = password, roomId = roomId)
                )
            }, {
                val room = getRoom()
                room?.parseLiveInfo()?.let { variable ->
                    LiveInitInfo(variable, room.userCount)
                }
            })

        }
    }

    //用户退出直播间
    val exitLiveLiveData = MutableLiveData<ExitLiveBean>()
    fun exitLive(anchorId: Long, exitLiveBean: ExitLiveBean, roomId: String? = null) {
        viewModelScope.launch {
            val deferred = async {
                withContext(NonCancellable + CoroutineScopeManager.ioDispatcher) {
                    try {
                        SmartFoxQueueManager.sendLiveMessage(
                            COMMAND_LIVE_QUIT,
                            LiveQuitMessage(anchorId, roomId)
                        )
                    } catch (_: Throwable) {
                    }
                }
            }

            withTimeoutOrNull(500) {
                deferred.await()
            }

            exitLiveLiveData.postValue(exitLiveBean)
        }
    }

}